import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-07-17
 * Time: 15:39
 */
public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        Connection connection=dataSource.getConnection();

        String sql="select * from student";

        PreparedStatement statement=connection.prepareStatement(sql);

        // 使用select语句的时候要用executeQuery
        // executeUpdate 只返回一个int
        // executeQuery 返回的是一个ResultSet对象,可以把这个对象视为是一个"临时表"
        ResultSet resultSet= statement.executeQuery();

        // 遍历临时表,拿到里面的数据
        while(resultSet.next()){
            String name=resultSet.getString("student_name");

            int age=resultSet.getInt("student_age");

            System.out.println(name+":"+age);
        }
    }
}
